/**
 * @(#)Server.java
 *
 *
 * @author
 * @version 1.00 2014/2/28
 */
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Server {

    private InetAddress inetaddress;
    private ServerSocket server;
    private Socket[] client = new Socket[5];
    private String message=null;
    private int connection=0;

    public Server(){
     	try{
     	message = JOptionPane.showInputDialog(new JFrame(),"Enter the local address");
     	if(message.equals(null)){
     		message = inetaddress.getCanonicalHostName();
     	}
     		inetaddress.getByName(message);
     		System.out.println("starting server with local address "+message);
    		System.out.println(inetaddress);
    		server = new ServerSocket(3333,1,inetaddress);
    		new Thread(new acceptClient()).start();
    	}
    	catch (Exception e){
    		System.out.println("Exception "+e);
    	}
    }

    public class acceptClient implements Runnable{

    	public void run() {
    		try{
    		while(true){
    			connection++;
    			client[connection] = server.accept();
    			new Thread(new clientHandler()).run();
    		}

    		}catch (Exception e){
    			System.out.println("Exception 1, "+e);
    		}
    	}

    }
    public class clientHandler implements Runnable{
	    	public void run(){
    		try{

    		BufferedReader line =
  			    new BufferedReader(new InputStreamReader(client[connection].getInputStream()));

  			PrintWriter lineout =
  				new PrintWriter(client[connection].getOutputStream(), true);

			  lineout.println("Welcome!");
    		while((message=line.readLine())!=null){
    			System.out.println("Client: "+message);
    			lineout.println(message);
    		}
    		}
    		catch (Exception e){
    			System.out.println(e);
    		}
    	}
    }
    public static void main(String[] args) {
        new Server();
    }
}
